Scroll Progress Bar

In C, an enum (short for enumeration) is a user-defined data type that consists of a set of named constants, known as enumerators. Each enumerator represents an integer value, and by default, the first enumerator has a value of 0, and subsequent enumerators have values incremented by 1 from the previous one.

Usage and Syntax:

To define an enum, use the enum keyword followedby the name of the enum and a list of enumerator names enclosed in curly braces.


    enum enum_name {
    enumerator1,
    enumerator2,
    ...
    };
    

By default, enum elements start from 0, but can explicitly assign values to enumerators.

Sample Code with Explanation and Output:

#include <stdio.h>

// Defining an enum for days of the week
enum Days {
    SUNDAY, // 0
    MONDAY, // 1
    TUESDAY, // 2
    WEDNESDAY, // 3
    THURSDAY, // 4
    FRIDAY, // 5
    SATURDAY // 6
};

int main() {
    enum Days today = WEDNESDAY;

    switch (today) {
        case SUNDAY:
            printf("Today is Sunday.\n");
            break;
        case MONDAY:
            printf("Today is Monday.\n");
            break;
        case TUESDAY:
            printf("Today is Tuesday.\n");
            break;
        case WEDNESDAY:
            printf("Today is Wednesday.\n"); // This case is executed
            break;
        case THURSDAY:
            printf("Today is Thursday.\n");
            break;
        case FRIDAY:
            printf("Today is Friday.\n");
            break;
        case SATURDAY:
            printf("Today is Saturday.\n");
            break;
        default:
            printf("Invalid day.\n");
    }

    return 0;
}
Output:

Today is Wednesday.
Explanation:
  • In the sample code, define an enum Days to represent the days of the week, starting from SUNDAY with the default value of 0.
  • Then create a variable today of type enum Days and initialize it with the enumerator WEDNESDAY, which has a value of 3.
  • The program then uses a switch statement to check the value of today and prints the corresponding day of the week using printf.
  • Since today is WEDNESDAY, the case WEDNESDAY is executed, and the output states that today is Wednesday.

What is an enum in C?


Enumeration

What is the purpose of an enum in C?


Constants

How are enum constants defined in C?


Values

What is the default type of an enum in C?


Int

How can you access enum constants in C?


Name